<?php

/**
 * Description of Auth
 *
 * @author markos
 */
class VirtualLabs_Auth {

    private $username;
    private $password;
    private $debugLogger;

    function __construct($user, $pass) {
        $this->username = $user;
        $this->password = $pass;
        $this->debugLogger = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
    }

    private function getUserInfo() {
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $userInfo = array();
        // client data
        $select = $db->select()
                ->from(array('usuario'), array('nombre', 'apellido', 'email', 'passw', 'tipo_usuario'))
                ->where("username = ?", $this->username);

        $result = $db->fetchRow($select);
        $userInfo["nombre"] = $result["nombre"];
        $userInfo["apellido"] = $result["apellido"];
        $userInfo["username"] = $this->username;
        $userInfo["email"] = $result["email"];
//        $userInfo["passw"] = $result["passw"];
        $userInfo["tipo_usuario"] = $result["tipo_usuario"];
        return $userInfo;
    }

    public function authenticate() {
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
        $authAdapter->setTableName(array('usuario'))
                ->setIdentityColumn('username')
                ->setCredentialColumn('passw')
                ->setIdentity($this->username)
                ->setCredential(VirtualLabs_Admin_Usuario::getPassword($this->password));
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapter);
        if ($result->isValid()) {
            // the default storage is a session with namespace Zend_Auth  
            $authStorage = $auth->getStorage();
            $userinfodebug = var_export($this->getUserInfo(), true);
            $this->debugLogger->debug($userinfodebug);
            $authStorage->write($this->getUserInfo());
            return true;
        } else {
            $this->debugLogger->debug("[ failed-login-attempted ]" . $this->username . "/" . $this->password);
        }
        return false;
    }

}

?>
